import 'dart:ffi';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'connect_type.dart';
import 'flutter_xprinter.dart';
import 'flutter_xprinter_platform_interface.dart';

/// An implementation of [FlutterXprinterPlatform] that uses method channels.
class MethodChannelFlutterXprinter extends FlutterXprinterPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_xprinter');
  var _handlers = [];

  MethodChannelFlutterXprinter() {
    methodChannel.setMethodCallHandler((call) async {
      for (var element in _handlers) {
        element(call.method, call.arguments);
      }
    });
  }

  @override
  void addMethodCallHandler(CallHandler handler) {
    _handlers.add(handler);
  }

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  void scanBluetoothDevices() {
    methodChannel.invokeMethod("scanBluetoothDevices");
  }

  @override
  void stopDiscovery() {
    methodChannel.invokeMethod("stopDiscovery");
  }

  @override
  void scanUsbDevices() {
    methodChannel.invokeMethod<String>("scanUsbDevices");
  }

  @override
  void connect(ConnectType connType, DeviceType deviceType, String address) {
    methodChannel.invokeMethod("connect", {
      "connType": connType.value,
      "deviceType": deviceType.value,
      "address": address,
    });
  }

  @override
  void disconnect(String address) {
    methodChannel.invokeMethod("disconnect", {
      "address": address,
    });
  }

  @override
  Future<int> sendPrintTask(List<int> bytes, ConnectType connType,
      DeviceType deviceType, String address) async {
    await methodChannel.invokeMethod<bool>("sendPrintTask", {
      "bytes": bytes,
      "connType": connType.value,
      "deviceType": deviceType.value,
      "address": address,
    });
    return 1;
  }
}
